package cn.com.dcsgo.mybatis.plus.controller;

import cn.com.dcsgo.mybatis.plus.domain.dto.UserFormDTO;
import cn.com.dcsgo.mybatis.plus.domain.po.User;
import cn.com.dcsgo.mybatis.plus.domain.query.UserQuery;
import cn.com.dcsgo.mybatis.plus.domain.vo.UserVO;
import cn.com.dcsgo.mybatis.plus.service.UserService;

import cn.hutool.core.bean.BeanUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author Dcsgo
 * @since 2024/8/28 10:33
 */
@Api(tags = "用户管理接口")
@RestController
@RequestMapping("users")
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;

    @ApiOperation("新增用户")
    @PostMapping
    public void saveUser(@RequestBody UserFormDTO userFormDTO) {
        User saveUser = BeanUtil.copyProperties(userFormDTO, User.class);
        userService.save(saveUser);
    }

    @ApiOperation("通过id删除用户")
    @DeleteMapping("{id}")
    public void deleteUser(@PathVariable Long id) {
        userService.removeById(id);
    }

    @ApiOperation("通过id获取用户")
    @GetMapping("{id}")
    public UserVO queryUserById(@PathVariable Long id) {
        User user = userService.getById(id);
        return BeanUtil.copyProperties(user, UserVO.class);
    }

    @ApiOperation("通过id集合获取用户")
    @GetMapping
    public List<UserVO> getUserByIds(@RequestParam("ids") List<Long> ids) {
        List<User> users = userService.listByIds(ids);
        return BeanUtil.copyToList(users, UserVO.class);
    }

    @ApiOperation("通过id扣减用户余额")
    @PutMapping("{id}/deduction/{money}")
    public void reduceBalance(@ApiParam("用户编号") @PathVariable Long id,
                              @ApiParam("扣减金额") @PathVariable Integer money) {
        userService.reduceBalance(id, money);
    }

    @ApiOperation("复杂条件查询用户")
    @GetMapping("list")
    public List<UserVO> queryUsers(UserQuery userQuery) {
        List<User> users = userService.queryUsers(
                userQuery.getName(),
                userQuery.getStatus(),
                userQuery.getMinBalance(),
                userQuery.getMaxBalance()
        );
        return BeanUtil.copyToList(users, UserVO.class);
    }
}
